<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

$this->useClass("Action_Community_FeedHandler");
class Action_Node_ShowNodeMembers extends Action_Community_FeedHandler {
	private $per_page = 20;
	private $lpage = 1;
	private $pages = 0;
	
	public function getFeedModel() {
		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
    $this->rh->UseClass("AggregatedModel_Feed_ReaderItems");
    return new AggregatedModel_Feed_ReaderItems();
	}
	
  public function process () {
		$aa = &$this->aa;
		
		$view = $this->rh->views->findByName('node_users');
		
		$view->data = $aa->template_data;
		
		$items = $this->getUsersList();
		
		$view->data['items'] = array();
		foreach ( $items as $item ) {
			$user = $this->ctx->store->getObject( $item['poster'] );
			if ( $user instanceof fobject ) {
				$user->data['oid'] = $user->id;
				$view->data['items'][] = $user->data;
			}
		}
		
		if ( $this->lpage > 1 ) {
			$view->data["prev_page"] = $this->lpage - 1;
		}
		if ( $this->pages > $this->lpage ) {
			$view->data["next_page"] = $this->lpage + 1;
		}
    
    $view->data['is_members'] = true;
		
		return $this->rh->response->setContent( $view );
  }
	
	private function getUsersList() {
    $sql = "select count(*) as count from {$this->ctx->store->db->db_prefix}class_user u " .
    " left join {$this->ctx->store->db->db_prefix}objects o on o.oid = u.oid " .
    ' where o.is_deleted = 0';
		
		$result = $this->ctx->store->query($sql);
		if ( !($result instanceof MysqlDBResult) ) {
			return 0;
		}
    
    $rec = $result->next();
    
  	$this->pages = (int) ($rec['count'] / $this->per_page);
		if ( $rec['count'] % $this->per_page > 0 ) {
			$this->pages++;
		}
		
		if ( isset($this->rh->REQUEST['lpage']) && !empty($this->rh->REQUEST['lpage']) ) {
			$this->lpage = abs($this->rh->REQUEST['lpage']+0);
    }
		
		if ( $this->lpage > $this->pages ) {
			$this->lpage = $this->pages;
		}
    
    $sql = "select max(if(c.oid > a.oid, c.oid, a.oid)) as max_oid, u.oid as poster " .
    " from {$this->ctx->store->db->db_prefix}class_user u " .
    " left join {$this->ctx->store->db->db_prefix}objects o on u.oid = o.oid " .
    " left join {$this->ctx->store->db->db_prefix}class_allfeed a on a.posted_by_id = u.oid and a.is_deleted = 0 " .
    " left join {$this->ctx->store->db->db_prefix}class_comment c on c.posted_by_id = u.oid and c.is_deleted = 0  " .
    " where o.is_deleted = 0 group by poster order by max_oid desc, u.oid desc " .
		" limit " . (($this->lpage - 1) * $this->per_page) . ", {$this->per_page}";
    
		$result = $this->ctx->store->query($sql);
		if ( !($result instanceof MysqlDBResult) ) {
			return 0;
		}
    
    $items = array();
    while ( $row = $result->next() ) {
      $items[] = $row;
    }
    
    return $items;		
	}
}